package com.fxz.rabbitmq.producer.broker;

import com.fxz.rabbitmq.api.enums.MessageTypeEnum;
import com.fxz.rabbitmq.api.exception.MessageException;
import com.fxz.rabbitmq.api.pojo.Message;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-08-17 14:21
 */
@Slf4j
@AllArgsConstructor
@Component
public class RabbitBrokerImpl implements RabbitBroker {

    private final RabbitTemplateContainer rabbitTemplateContainer;

    /**
     * 发送消息的核心方法 使用异步线程池发送消息
     *
     * @param message
     */
    private void sendKernel(Message message) {
        AsyncBaseQueue.submit((Runnable) () -> {
            String topic = message.getTopic();
            String routingKey = message.getRoutingKey();
            CorrelationData correlationData = new CorrelationData(
                    String.format(
                            "%s#%s",
                            message.getMessageId(),
                            System.currentTimeMillis()));
            RabbitTemplate rabbitTemplate = null;
            try {
                rabbitTemplate = rabbitTemplateContainer.getTemplate(message);
                rabbitTemplate.convertAndSend(topic, routingKey, message, correlationData);
                log.info("#RabbitBrokerImpl.sendKernel# send to rabbitmq,messageId:{}", message.getMessageId());
            } catch (MessageException e) {
                e.printStackTrace();
            }
        });

    }

    /**
     * 发送迅速消息
     *
     * @param message
     */
    @Override
    public void rapidSend(Message message) {
        message.setMessageType(MessageTypeEnum.RAPID.getCode());
        sendKernel(message);
    }


    @Override
    public void confirmSend(Message message) {

    }

    @Override
    public void reliantSend(Message message) {

    }

    @Override
    public void sendMessages() {

    }
}
